package com.wyclabs.gateway.component;


import com.wyclabs.commons.constants.ServiceName;
import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * 聚合swagger
 * @author Wyccc
 * @date 2019/10/29
 */
@Component
@Primary
@AllArgsConstructor
public class RegistrySwaggerResourcesProvider implements SwaggerResourcesProvider {

    private final RouteLocator routeLocator;

    @Override
    public List<SwaggerResource> get() {
        //根据所有的服务，找到服务swagger自动生成的文档地址
        List<SwaggerResource> resources = new ArrayList<>();
        routeLocator.getRoutes().toStream().forEach(route -> {
            resources.add(swaggerResource((ServiceName.getDescByKey(route.getId())), route.getUri().getPath().replace("**", "v2/api-docs")));
        });
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}